package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.service.ProFormExplainService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.FormExplainAddBatchDTO;
import com.xbongbong.pro.formexplain.pojo.vo.FormExplainAddBatchVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 吴峰
 * @date 2022/10/28 14:10
 */
@Service("proFormExplainService")
public class ProFormExplainServiceImpl implements ProFormExplainService {

    private static final Logger LOG = LoggerFactory.getLogger(ProFormExplainServiceImpl.class);
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    @Override
    public FormExplainAddBatchVO addBatch(FormExplainAddBatchDTO formExplainAddBatchDTO) throws XbbException {
        FormExplainAddBatchVO formExplainAddBatchVO = new FormExplainAddBatchVO();
        try {
            List<PaasFormExplainEntity> formExplainList = new ArrayList<>();
            formExplainAddBatchDTO.getFormExplainList().forEach((item) -> {
                PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
                BeanUtil.copyProperties(item, paasFormExplainEntity);
                paasFormExplainEntity.setCreatorId(formExplainAddBatchDTO.getUserId());
                paasFormExplainEntity.setExplains(JSON.toJSONString(item.getFormList()));
                long now = DateUtil.getInt();
                paasFormExplainEntity.setAddTime(now);
                paasFormExplainEntity.setUpdateTime(now);
                formExplainList.add(paasFormExplainEntity);
            });
            if (!formExplainList.isEmpty()) {
                List<PaasFormExplainEntity> formExplainResultList = paasFormExplainModel.insertBatch(formExplainList);
                formExplainAddBatchVO.setFormExplainList(formExplainResultList);
            }
        } catch (Exception e) {
            LOG.error("formExplainServiceImpl.addBatch新建表单字段信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formExplainAddBatchVO;
    }
}
